/**
 * Copyright (c) 2004-2015 All Rights Reserved.
 */
package com.zbest.component.monitor;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * dal-digest.log,service-digest.log
 *
 * @author czhou3306@gmail.com
 * @version $Id: DalMethodMonitorInterceptor.java, v0.1 2015年6月3日 上午10:19:44 czhou3306@gmail.com Exp $
 */
public class SysMethodMonitorInterceptor implements MethodInterceptor {

    /**输出的日志名*/
    private String loggerName;

    /** 
     * @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
     */
    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {

        long startTime = System.currentTimeMillis();

        boolean success = true;
        try {
            return invocation.proceed();
        } catch (Exception ex) {
            success = false;
            throw ex;
        } finally {
            long escapeTime = System.currentTimeMillis() - startTime;

            this.printLog(invocation, escapeTime, success);
        }
    }

    /**
     * 打印日志
     * 
     * @param invocation
     * @param escapeTime
     * @param success
     */
    private void printLog(MethodInvocation invocation, long escapeTime, boolean success) {
        String method = invocation.getMethod().getDeclaringClass().getSimpleName()
                        + MonitorConstant.METHOD_CONNECT + invocation.getMethod().getName();

        StringBuilder sb = new StringBuilder();
        sb.append(MonitorConstant.MONITOR_START);
        sb.append(MonitorConstant.SUB_START);

        sb.append(method);
        sb.append(MonitorConstant.PARAM_SEPERATOR);
        sb.append(success ? MonitorConstant.SUCCESS : MonitorConstant.FAIL);
        sb.append(MonitorConstant.PARAM_SEPERATOR);
        sb.append(escapeTime);
        sb.append(MonitorConstant.TIME_UNIT);
        sb.append(MonitorConstant.SUB_END);
        sb.append(MonitorConstant.MONITOR_END);
        Logger logger = LoggerFactory.getLogger(loggerName);
        if (logger != null) {
            logger.info(sb.toString());
        }
    }

    /**
     * Setter method for property <tt>loggerName</tt>.
     * 
     * @param loggerName value to be assigned to property loggerName
     */
    public void setLoggerName(String loggerName) {
        this.loggerName = loggerName;
    }

}
